package util
{
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.geom.Rectangle;

	public class DisplayUtils
	{
		public function DisplayUtils()
		{
		}
		
		public function calculateOpaqueSize( displayObject:DisplayObject ):Rectangle
		{
			var testBitmapData:BitmapData = new BitmapData( displayObject.width, displayObject.height,true, 0x00ffffff  );
			
			testBitmapData.draw( displayObject, null, null, null, null, true );
			
			
			var hRange:Array = computeOpaqueRange( displayObject.width, displayObject.height,function( i:int, j:int ):uint
				{
					return testBitmapData.getPixel( i, j );
				}
 			);
			
			if( !hRange ) 
				return new Rectangle( 0, 0, displayObject.width, displayObject.height );
			
			var vRange:Array = computeOpaqueRange( displayObject.height, displayObject.width, function( i:int, j:int ):uint
				{
					return testBitmapData.getPixel( j, i );
				}
			);
			
			if( !vRange )
				return new Rectangle( 0, 0, displayObject.width, displayObject.height );
			
			
			return new Rectangle( hRange[0], vRange[0], hRange[1] - hRange[0], vRange[1] - vRange[0] );
			
		}
		
		
		private function computeOpaqueRange( len1:Number, len2:Number, pixelFunc:Function ):Array
		{
			var i:int;
			
			var j:int;
			
			var n:int;
			
			var p:uint;
			
			var minVal:int = -1;
			
			var maxVal:int = -1;
			
			for( i = 0, j = len1 - 1; i < j && !finded; i++,j-- )
			{
				for( n = 0; n < len2; n++ )
				{
					if(  minVal < 0 )
					{
						p = pixelFunc( i, n );
						
						minVal = p & 0xFF000000 > 0 ? i : minVal;
						
					}
					
					if( maxVal < 0 )
					{
						p =  pixelFunc( j, n );;
						
						maxVal =  p & 0xFF000000 > 0 ? i : maxVal;
					}
					
					if( minVal >= 0 && maxVal >= 0 )
					{
						break;
					}
					
				}
				
			}
			
			if( minVal >= 0 && maxVal >= 0 )
			{
				return null;
			}
			
			return [minVal, maxVal];
			
		}
		
	}
}